/**
 * @Date 2023-02-24 13:46:57
 * @Remark
 */

// react
import React, { useEffect } from "react";
// lib
import { Modal, Form, Input } from "antd";
// components & widget
// style
// config
import { MODULE_NAME } from "./config";
import { MODAL_STYLE, TEXTAREA_PROPS } from "project/config";
import { DESC_LENGTH_RULE, INPUT_REQUIRED_RULE } from "project/validRules";
// script & methods & public
// store
import { observer } from "mobx-react";
import { state } from "./state";
// controller
import { addRole, updateRole } from "./controller";
// interface
// 其它

function EditModal() {
  const [form] = Form.useForm();

  const show = state.editModalShow;
  const title = `${state.editInfo ? "编辑" : "添加"}${MODULE_NAME}`;

  useEffect(() => {
    if (show) {
      form.resetFields();
    }
    if (state.editInfo) {
      const info = state.editInfo;
      form.setFieldsValue({
        ...info,
      });
    }
    return () => {
      //
    };
  }, [form, show]);

  const handleCancel = () => {
    state.editModal = false;
  };

  const handleOk = async () => {
    try {
      const result = await form.validateFields();
      if (state.editInfo) {
        updateRole(result, state.editInfo.id);
      } else {
        addRole(result);
      }
    } catch (error) {
      //
    }
  };

  return (
    <Modal
      title={title}
      open={show}
      onCancel={handleCancel}
      onOk={handleOk}
      destroyOnClose
      maskClosable
      forceRender
      okButtonProps={{
        loading: state.editModalLoading,
      }}
    >
      <Form {...MODAL_STYLE.FORM_6_15} form={form}>
        <Form.Item
          name="name"
          label="角色名称"
          rules={[INPUT_REQUIRED_RULE]}
        >
          <Input />
        </Form.Item>
        {/* <Form.Item
          name="roleCode"
          label="角色编码"
          extra="编码必须是大写字母和下划线组成"
          normalize={(value) => {
            return value.toUpperCase().replace(/[^A-Z_]/g, "");
          }}
          rules={[INPUT_REQUIRED_RULE]}
        >
          <Input />
        </Form.Item> */}
        <Form.Item
          name="description"
          label="角色说明"
          rules={[DESC_LENGTH_RULE]}
        >
          <Input.TextArea
            {...TEXTAREA_PROPS}
            allowClear
            autoSize={{ minRows: 3, maxRows: 3 }}
          />
        </Form.Item>
      </Form>
    </Modal>
  );
}

export default observer(EditModal);
